import 'package:flutter/material.dart';
import '../../core/elegance_theme.dart';

/// 分页组件大小枚举
enum EPaginationSize {
  /// 小型分页
  small,
  
  /// 普通分页
  normal,
}

/// 分页组件
class EPagination extends StatefulWidget {
  /// 创建EPagination组件
  const EPagination({
    super.key,
    required this.total,
    this.currentPage = 1,
    this.pageSize = 10,
    this.pageSizes = const [10, 20, 50, 100],
    this.layout = 'total, sizes, prev, pager, next, jumper',
    this.size = EPaginationSize.normal,
    this.background = false,
    this.onChange,
    this.onSizeChange,
  });

  /// 总条数
  final int total;
  
  /// 当前页码
  final int currentPage;
  
  /// 每页条数
  final int pageSize;
  
  /// 每页条数选项
  final List<int> pageSizes;
  
  /// 布局配置
  final String layout;
  
  /// 分页组件大小
  final EPaginationSize size;
  
  /// 是否显示背景
  final bool background;
  
  /// 页码改变回调
  final Function(int page, int pageSize)? onChange;
  
  /// 每页条数改变回调
  final Function(int pageSize)? onSizeChange;
  
  @override
  _EPaginationState createState() => _EPaginationState();
}

class _EPaginationState extends State<EPagination> {
  late int _currentPage;
  late int _pageSize;
  late int _totalPages;
  
  @override
  void initState() {
    super.initState();
    _currentPage = widget.currentPage;
    _pageSize = widget.pageSize;
    _updateTotalPages();
  }
  
  @override
  void didUpdateWidget(covariant EPagination oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (
      oldWidget.total != widget.total ||
      oldWidget.currentPage != widget.currentPage ||
      oldWidget.pageSize != widget.pageSize
    ) {
      _currentPage = widget.currentPage;
      _pageSize = widget.pageSize;
      _updateTotalPages();
    }
  }
  
  /// 更新总页数
  void _updateTotalPages() {
    _totalPages = (widget.total / _pageSize).ceil();
    // 确保当前页不超过总页数
    if (_currentPage > _totalPages && _totalPages > 0) {
      _currentPage = _totalPages;
    }
  }
  
  /// 处理页码改变
  void _handlePageChange(int page) {
    if (page < 1 || page > _totalPages || page == _currentPage) {
      return;
    }
    
    setState(() {
      _currentPage = page;
    });
    
    if (widget.onChange != null) {
      widget.onChange!(_currentPage, _pageSize);
    }
  }
  
  /// 处理每页条数改变
  void _handleSizeChange(int size) {
    if (size == _pageSize) {
      return;
    }
    
    setState(() {
      _pageSize = size;
      // 重置为第一页
      _currentPage = 1;
      _updateTotalPages();
    });
    
    if (widget.onSizeChange != null) {
      widget.onSizeChange!(_pageSize);
    }
    
    if (widget.onChange != null) {
      widget.onChange!(_currentPage, _pageSize);
    }
  }
  
  /// 构建页码按钮
  Widget _buildPageButton(int page, {bool isCurrent = false}) {
    final theme = EleganceTheme.of(context);
    final buttonSize = widget.size == EPaginationSize.small ? 28.0 : 32.0;
    final fontSize = widget.size == EPaginationSize.small ? 12.0 : 14.0;
    
    final isDisabled = page < 1 || page > _totalPages;
    
    return Container(
      width: buttonSize,
      height: buttonSize,
      margin: const EdgeInsets.symmetric(horizontal: 2.0),
      child: TextButton(
        style: TextButton.styleFrom(
          backgroundColor: isCurrent 
            ? theme.primaryColor 
            : (widget.background ? Colors.white : Colors.transparent),
          foregroundColor: isCurrent 
            ? Colors.white 
            : (isDisabled ? theme.textPlaceholderColor : theme.textRegularColor),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(4.0),
            side: BorderSide(
              color: widget.background 
                ? theme.borderColor 
                : (isCurrent ? theme.primaryColor : Colors.transparent),
              width: 1.0,
            ),
          ),
          padding: EdgeInsets.zero,
          textStyle: TextStyle(
            fontSize: fontSize,
          ),
        ),
        onPressed: isDisabled ? null : () => _handlePageChange(page),
        child: Text('$page'),
      ),
    );
  }
  
  /// 构建上一页/下一页按钮
  Widget _buildNavButton(String icon, bool isPrev) {
    final theme = EleganceTheme.of(context);
    final buttonSize = widget.size == EPaginationSize.small ? 28.0 : 32.0;
    
    final isDisabled = isPrev ? _currentPage <= 1 : _currentPage >= _totalPages;
    
    return Container(
      width: buttonSize,
      height: buttonSize,
      margin: const EdgeInsets.symmetric(horizontal: 2.0),
      child: TextButton(
        style: TextButton.styleFrom(
          backgroundColor: widget.background ? Colors.white : Colors.transparent,
          foregroundColor: isDisabled 
            ? theme.textPlaceholderColor 
            : theme.textRegularColor,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(4.0),
            side: BorderSide(
              color: widget.background ? theme.borderColor : Colors.transparent,
              width: 1.0,
            ),
          ),
          padding: EdgeInsets.zero,
        ),
        onPressed: isDisabled 
          ? null 
          : () => _handlePageChange(isPrev ? _currentPage - 1 : _currentPage + 1),
        child: Text(icon),
      ),
    );
  }
  
  /// 构建页码列表
  Widget _buildPageList() {
    final List<Widget> pages = [];
    
    // 如果总页数较少，直接显示所有页码
    if (_totalPages <= 7) {
      for (int i = 1; i <= _totalPages; i++) {
        pages.add(_buildPageButton(i, isCurrent: i == _currentPage));
      }
    } else {
      // 显示当前页附近的页码和省略号
      if (_currentPage <= 4) {
        // 当前页在前4页
        for (int i = 1; i <= 5; i++) {
          pages.add(_buildPageButton(i, isCurrent: i == _currentPage));
        }
        pages.add(const Text('...'));
        pages.add(_buildPageButton(_totalPages));
      } else if (_currentPage >= _totalPages - 3) {
        // 当前页在后4页
        pages.add(_buildPageButton(1));
        pages.add(const Text('...'));
        for (int i = _totalPages - 4; i <= _totalPages; i++) {
          pages.add(_buildPageButton(i, isCurrent: i == _currentPage));
        }
      } else {
        // 当前页在中间
        pages.add(_buildPageButton(1));
        pages.add(const Text('...'));
        for (int i = _currentPage - 1; i <= _currentPage + 1; i++) {
          pages.add(_buildPageButton(i, isCurrent: i == _currentPage));
        }
        pages.add(const Text('...'));
        pages.add(_buildPageButton(_totalPages));
      }
    }
    
    return Row(children: pages);
  }
  
  /// 构建每页条数选择器
  Widget _buildSizeSelector() {
    final theme = EleganceTheme.of(context);
    final fontSize = widget.size == EPaginationSize.small ? 12.0 : 14.0;
    
    return DropdownButton<int>(
      value: _pageSize,
      items: widget.pageSizes.map((size) {
        return DropdownMenuItem<int>(
          value: size,
          child: Text('$size', style: TextStyle(fontSize: fontSize)),
        );
      }).toList(),
      onChanged: (size) {
        if (size != null) {
          _handleSizeChange(size);
        }
      },
      underline: Container(
        height: 1,
        color: theme.borderColor,
      ),
      style: TextStyle(
        fontSize: fontSize,
        color: theme.textRegularColor,
      ),
      iconSize: 16.0,
    );
  }
  
  /// 构建页码跳转器
  Widget _buildJumper() {
    final theme = EleganceTheme.of(context);
    final fontSize = widget.size == EPaginationSize.small ? 12.0 : 14.0;
    final inputWidth = widget.size == EPaginationSize.small ? 40.0 : 45.0;
    
    late TextEditingController _controller;
    
    // 初始化控制器
    _controller = TextEditingController(text: '$_currentPage');
    
    void _handleJump() {
      final page = int.tryParse(_controller.text);
      if (page != null) {
        _handlePageChange(page);
      }
    }
    
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text('前往', style: TextStyle(fontSize: fontSize, color: theme.textRegularColor)),
        Container(
          width: inputWidth,
          margin: const EdgeInsets.symmetric(horizontal: 8.0),
          child: TextField(
            controller: _controller,
            keyboardType: TextInputType.number,
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: fontSize),
            decoration: InputDecoration(
              contentPadding: EdgeInsets.zero,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(4.0),
                borderSide: BorderSide(color: theme.borderColor),
              ),
              isDense: true,
            ),
            onSubmitted: (value) => _handleJump(),
          ),
        ),
        Text('页', style: TextStyle(fontSize: fontSize, color: theme.textRegularColor)),
        const SizedBox(width: 8.0),
        TextButton(
          onPressed: _handleJump,
          style: TextButton.styleFrom(
            backgroundColor: theme.primaryColor,
            foregroundColor: Colors.white,
            textStyle: TextStyle(fontSize: fontSize),
            padding: const EdgeInsets.symmetric(horizontal: 12.0),
            minimumSize: Size(0, widget.size == EPaginationSize.small ? 28.0 : 32.0),
          ),
          child: Text('确定'),
        ),
      ],
    );
  }
  
  @override
  Widget build(BuildContext context) {
    final theme = EleganceTheme.of(context);
    final fontSize = widget.size == EPaginationSize.small ? 12.0 : 14.0;
    
    final List<Widget> components = [];
    final layoutItems = widget.layout.split(', ');
    
    // 构建各个布局组件
    for (final item in layoutItems) {
      switch (item) {
        case 'total':
          components.add(
            Text(
              '共 $widget.total 条', 
              style: TextStyle(fontSize: fontSize, color: theme.textRegularColor)
            ),
          );
          break;
        case 'sizes':
          components.add(
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text('每页', style: TextStyle(fontSize: fontSize, color: theme.textRegularColor)),
                _buildSizeSelector(),
                Text('条', style: TextStyle(fontSize: fontSize, color: theme.textRegularColor)),
              ],
            ),
          );
          break;
        case 'prev':
          components.add(_buildNavButton('<', true));
          break;
        case 'pager':
          if (_totalPages > 0) {
            components.add(_buildPageList());
          }
          break;
        case 'next':
          components.add(_buildNavButton('>', false));
          break;
        case 'jumper':
          if (_totalPages > 0) {
            components.add(_buildJumper());
          }
          break;
      }
      
      // 添加分隔符
      if (item != layoutItems.last) {
        components.add(const SizedBox(width: 12.0));
      }
    }
    
    // 容器背景
    final container = Container(
      padding: widget.size == EPaginationSize.small 
        ? const EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0) 
        : const EdgeInsets.symmetric(horizontal: 15.0, vertical: 10.0),
      decoration: BoxDecoration(
        color: widget.background ? theme.surfaceColor : Colors.transparent,
        border: widget.background 
          ? Border.all(color: theme.borderColor, width: 1.0) 
          : null,
        borderRadius: BorderRadius.circular(4.0),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: components,
      ),
    );
    
    return container;
  }
}